<template>
    <div class="alumni-manage-page">
        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 右侧内容区域 -->
            <main class="manage-main">
                <div class="manage-container">
                    <!-- 页面标题和操作按钮 -->
                    <div class="page-header">
                        <h1 class="page-title">校友管理</h1>
                        <el-button type="primary" @click="handleCreateAlumni">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            新增校友
                        </el-button>
                    </div>

                    <!-- 搜索和筛选区域 -->
                    <div class="filter-section">
                        <div class="search-group">
                            <el-input v-model="searchKeyword" placeholder="搜索学号、姓名或手机号..." class="search-input"
                                @keyup.enter="handleSearch" clearable @clear="handleClearSearch">
                                <template #prefix>
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                搜索
                            </el-button>
                            <el-button @click="handleReset">重置</el-button>
                        </div>
                    </div>

                    <!-- 校友列表表格 -->
                    <div class="table-section">
                        <el-table :data="alumniList" v-loading="loading" style="width: 100%">
                            <el-table-column prop="id" label="ID" width="80" />
                            <el-table-column prop="student_id" label="学号" width="120" />
                            <el-table-column prop="real_name" label="姓名" width="120" />
                            <el-table-column prop="phone" label="手机号" width="130">
                                <template #default="{ row }">
                                    {{ row.phone || '-' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="major" label="专业" min-width="150" />
                            <el-table-column prop="grade" label="年级" width="100" />
                            <el-table-column prop="college" label="学院" min-width="150" />
                            <el-table-column label="认证状态" width="100" align="center">
                                <template #default="{ row }">
                                    <el-tag :type="row.status ? 'info' : 'success'" size="small">
                                        {{ row.status ? '未认证' : '已认证' }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column label="创建时间" width="180">
                                <template #default="{ row }">
                                    {{ formatTime(row.created_at) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" size="small" @click="handleEditAlumni(row)">
                                        编辑
                                    </el-button>
                                    <el-button type="danger" size="small" @click="handleDeleteAlumni(row.id)"
                                        :loading="row.deleting">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页组件 -->
                    <div v-if="alumniList.length > 0" class="pagination-section">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 50, 100]" :small="false" :disabled="false" :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </main>
        </div>

        <!-- 新增/编辑校友模态框 -->
        <el-dialog v-model="alumniDialogVisible" :title="alumniDialogTitle" width="600px"
            :before-close="handleCloseDialog">
            <el-form ref="alumniFormRef" :model="alumniForm" :rules="alumniRules" label-width="100px">
                <el-form-item label="学号" prop="student_id">
                    <el-input v-model="alumniForm.student_id" placeholder="请输入学号" maxlength="20" />
                </el-form-item>
                <el-form-item label="姓名" prop="real_name">
                    <el-input v-model="alumniForm.real_name" placeholder="请输入姓名" maxlength="50" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="alumniForm.phone" placeholder="请输入手机号" maxlength="11" />
                </el-form-item>
                <el-form-item label="年级" prop="grade">
                    <el-input v-model="alumniForm.grade" placeholder="请输入年级" maxlength="20" />
                </el-form-item>
                <el-form-item label="专业" prop="major">
                    <el-input v-model="alumniForm.major" placeholder="请输入专业" maxlength="50" />
                </el-form-item>
                <el-form-item label="学院" prop="college">
                    <el-input v-model="alumniForm.college" placeholder="请输入学院" maxlength="50" />
                </el-form-item>
                <!-- 编辑时显示状态，新增时不显示 -->
                <el-form-item v-if="isEditing" label="状态" prop="status">
                    <el-radio-group v-model="alumniForm.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCloseDialog">取消</el-button>
                    <el-button type="primary" @click="handleSubmitAlumni" :loading="submitting">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { useAlumniStore } from '@/stores/alumni'

const alumniStore = useAlumniStore()

// 响应式数据
const searchKeyword = ref('')
const loading = ref(false)
const isSearching = ref(false)
const submitting = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 校友列表
const alumniList = ref([])

// 模态框相关
const alumniDialogVisible = ref(false)
const alumniFormRef = ref(null)
const alumniForm = ref({
    student_id: '',
    real_name: '',
    phone: '',
    grade: '',
    major: '',
    college: '',
    status: 1
})
const isEditing = ref(false)
const editingAlumniId = ref(null)

// 计算对话框标题
const alumniDialogTitle = computed(() => {
    return isEditing.value ? '编辑校友' : '新增校友'
})

// 表单验证规则
const alumniRules = {
    student_id: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { min: 12, max: 12, message: '长度在 12 个字符', trigger: 'blur' }
    ],
    real_name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    grade: [
        { required: true, message: '请输入年级', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    major: [
        { required: true, message: '请输入专业', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    college: [
        { required: true, message: '请输入学院', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ]
}

// 初始化加载
onMounted(() => {
    fetchAlumnis()
})

// 监听分页变化
watch([currentPage, pageSize], () => {
    if (!isSearching.value) {
        fetchAlumnis()
    } else {
        handleSearch()
    }
})

// 获取校友列表
const fetchAlumnis = async () => {
    try {
        loading.value = true
        const response = await alumniStore.fetchAlumnisAction({
            page: currentPage.value,
            pageSize: pageSize.value
        })
        if (response.code === 0) {
            alumniList.value = response.data.list || []
            total.value = response.data.pagination?.total || alumniList.value.length
        }
    } catch (error) {
        ElMessage.error('获取校友列表失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 搜索校友
const handleSearch = async () => {
    if (!searchKeyword.value.trim()) {
        ElMessage.warning('请输入搜索关键词')
        return
    }

    try {
        loading.value = true
        isSearching.value = true
        currentPage.value = 1

        const response = await alumniStore.searchAlumnisAction({
            keyword: searchKeyword.value.trim()
        })
        if (response.code === 0) {
            alumniList.value = response.data.list || []
            total.value = response.data.pagination?.total || alumniList.value.length
            ElMessage.success(`找到 ${total.value} 条相关校友记录`)
        }
    } catch (error) {
        ElMessage.error('搜索失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 清空搜索
const handleClearSearch = () => {
    searchKeyword.value = ''
    isSearching.value = false
    currentPage.value = 1
    fetchAlumnis()
}

// 重置搜索
const handleReset = () => {
    searchKeyword.value = ''
    isSearching.value = false
    currentPage.value = 1
    fetchAlumnis()
}

// 每页条数变化
const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
}

// 当前页变化
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage
}

// 新增校友
const handleCreateAlumni = () => {
    isEditing.value = false
    editingAlumniId.value = null
    alumniForm.value = {
        student_id: '',
        real_name: '',
        phone: '',
        grade: '',
        major: '',
        college: '',
        status: 1
    }
    alumniDialogVisible.value = true
}

// 编辑校友
const handleEditAlumni = (alumni) => {
    isEditing.value = true
    editingAlumniId.value = alumni.id
    alumniForm.value = {
        student_id: alumni.student_id,
        real_name: alumni.real_name,
        phone: alumni.phone || '',
        grade: alumni.grade,
        major: alumni.major,
        college: alumni.college,
        status: alumni.status || 1
    }
    alumniDialogVisible.value = true
}

// 提交校友表单
const handleSubmitAlumni = async () => {
    if (!alumniFormRef.value) return

    try {
        await alumniFormRef.value.validate()
        submitting.value = true

        if (isEditing.value) {
            // 编辑校友
            const response = await alumniStore.updateAlumniAction(editingAlumniId.value, alumniForm.value)
            if (response.code === 0) {
                ElMessage.success('更新校友成功')
                alumniDialogVisible.value = false
                fetchAlumnis()
            }
        } else {
            // 新增校友 - 默认未认证状态
            const formData = {
                ...alumniForm.value,
                verified: 1 // 默认未认证
            }
            const response = await alumniStore.createAlumniAction(formData)
            if (response.code === 0) {
                ElMessage.success('创建校友成功')
                alumniDialogVisible.value = false
                fetchAlumnis()
            }
        }
    } catch (error) {
        if (error.errors) {
            ElMessage.warning('请完善表单信息')
        } else {
            ElMessage.error((isEditing.value ? '更新' : '创建') + '校友失败：' + error.message)
        }
    } finally {
        submitting.value = false
    }
}

// 删除校友
const handleDeleteAlumni = async (alumniId) => {
    try {
        await ElMessageBox.confirm('确定要删除这个校友吗？此操作不可恢复。', '确认删除', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        const alumni = alumniList.value.find(a => a.id === alumniId)
        if (alumni) {
            alumni.deleting = true
        }

        const response = await alumniStore.deleteAlumniAction(alumniId)
        if (response.code === 0) {
            ElMessage.success('删除校友成功')
            fetchAlumnis()
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消删除')
        } else {
            ElMessage.error('删除校友失败：' + error.message)
        }
    } finally {
        const alumni = alumniList.value.find(a => a.id === alumniId)
        if (alumni) {
            alumni.deleting = false
        }
    }
}

// 关闭对话框
const handleCloseDialog = () => {
    alumniDialogVisible.value = false
    alumniFormRef.value?.clearValidate()
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return ''
    return new Date(timeString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.alumni-manage-page {
    min-height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
}

/* 主内容区域 */
.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.manage-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    margin-left: 20px;
}

.manage-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 页面标题 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
}

.page-title {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

/* 筛选区域 */
.filter-section {
    margin-bottom: 20px;
}

.search-group {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-input {
    width: 300px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 24px;
}

/* 分页 */
.pagination-section {
    display: flex;
    justify-content: center;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .manage-main {
        margin-left: 240px;
        padding: 16px;
    }

    .manage-container {
        padding: 16px;
    }

    .page-header {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }

    .search-group {
        flex-direction: column;
        align-items: stretch;
    }

    .search-input {
        width: 100%;
    }
}
</style>